package service

import (
	"errors"
	"fmt"
	"net/http"
	"strings"

	"github.com/aliyun/alibabacloud-kms-agent/internal/model"
)

func getSecretParams(r *http.Request, pathPrefix string) (*model.GetSecretParams, error) {
	var params *model.GetSecretParams
	var err error

	if r.URL.Path == QueryStylePath {
		params, err = getParamsFromQuery(r)
	}

	if strings.HasPrefix(r.URL.Path, pathPrefix) {
		params, err = getParamsFromPath(r, pathPrefix)
	}

	return params, err
}

func getParamsFromQuery(r *http.Request) (*model.GetSecretParams, error) {
	params := &model.GetSecretParams{}
	query := r.URL.Query()

	if val, exists := query[QueryParamsSecretId]; exists {
		params.SecretID = val[0]
	} else {
		return nil, errors.New("missing parameter secretId")
	}

	if val, exists := query[QueryParamsVersionId]; exists {
		params.VersionID = val[0]
	}
	// Compatible with vault format
	if val, exists := query[QueryParamsVersion]; exists {
		params.VersionID = val[0]
	}
	if val, exists := query[QueryParamsVersionStage]; exists {
		params.VersionStage = val[0]
	}
	for param := range query {
		if param != QueryParamsSecretId && param != QueryParamsVersionId && param != QueryParamsVersion && param != QueryParamsVersionStage {
			return nil, fmt.Errorf("unknown parameter: %s", param)
		}
	}
	return params, nil
}

func getParamsFromPath(r *http.Request, pathPrefix string) (*model.GetSecretParams, error) {
	params := &model.GetSecretParams{}
	secretPath := r.URL.Path
	if !strings.HasPrefix(secretPath, pathPrefix) || len(secretPath) <= len(pathPrefix) {
		return nil, errors.New("missing secret ID")
	}
	params.SecretID = secretPath[len(pathPrefix):]

	query := r.URL.Query()
	if val, exists := query[QueryParamsVersionId]; exists {
		params.VersionID = val[0]
	}
	// Compatible with vault format
	if val, exists := query[QueryParamsVersion]; exists {
		params.VersionID = val[0]
	}
	if val, exists := query[QueryParamsVersionStage]; exists {
		params.VersionStage = val[0]
	}
	for param := range query {
		if param != QueryParamsVersionId && param != QueryParamsVersion && param != QueryParamsVersionStage {
			return nil, fmt.Errorf("unknown parameter: %s", param)
		}
	}
	return params, nil
}
